<script setup>
import { ref, onMounted, reactive, onBeforeUnmount } from "vue";
import api from "@/api";
import * as echarts from "echarts";
import _ from "lodash";
import { formatDate, cardHide } from "@/utils/common";
import { ElMessage } from "element-plus";

import nameIcon from "@/assets/images/staff/name.png";
import worktypeIcon from "@/assets/images/staff/worktype.png";
import teamIcon from "@/assets/images/staff/team.png";
import enterpriseIcon from "@/assets/images/staff/enterprise.png";

import moment from "moment";

let jobTypeChartRef = ref();
let entrySituationChartRef = ref();

let myJobTypeChart = null;
let myEntrySituationChart = null;

const topData = reactive({
  fieldCondition: {
    onSiteNum: "--",
    attendanceNum: "--",
  },
  jobTypeStatistics: {
    typeArr: [],
    numArr: [],
  },
  entryTrend: {
    hours: [],
    yData: [
      {
        title: "进场",
        value: [],
      },
      {
        title: "出场",
        value: [],
      },
    ],
  },
});

const bottomData = reactive({
  personName: "",
  pageSize: 20,
  total: 0,
  currentRowKey: "", //当前行的key
  form: {
    searchText: "",
    pageIndex: 0,
  },

  tableData: [],
  detailInfo: {
    baseInfo: {},
    simpleInfo: [
      {
        src: nameIcon,
        value: "",
        label: "姓名",
      },
      {
        src: worktypeIcon,
        value: "",
        label: "工种",
      },
      {
        src: teamIcon,
        value: "",
        label: "班组",
      },
      {
        src: enterpriseIcon,
        value: "",
        label: "参建单位",
      },
    ],
  },
});

onMounted(() => {
  initStaffTop();
  initStaffTable();
});

// 卸载页面销毁 window.onresize事件
onBeforeUnmount(() => {
  window.onresize = null;
});

const errorTip = ref("");
const topLoading = ref(false);
const initStaffTop = () => {
  topLoading.value = true;
  api.staff
    .getDailyStatistic({
      date: moment().format("YYYY-MM-DD"),
    })
    .then((res) => {
      topLoading.value = false;
      if (res.data.success) {
        console.log(res.data)
        //当前在场人数 今日考勤人数
        topData.fieldCondition.onSiteNum = res.data.currentPresentNum;
        // let now = new Date()
        // let hour = now.getHours()
        // console.log(hour)
        // console.log(res.data.todayAttendenceNum)
        // let currentStay = 0
        // let todayTotalNUm = 0
        // for(let i=0;i<res.data.todayAttendenceTrend.length;i++){
        //   if(i>=hour){
        //     res.data.todayAttendenceTrend[i].inNum = 0;
        //   res.data.todayAttendenceTrend[i].outNum = 0
        //   console.log(1)
        //   }
        //   else{
        //     todayTotalNUm
        //   }
       
        // }
        topData.fieldCondition.attendanceNum = res.data.todayAttendenceNum;

        //今日考勤工种及人数分布
        res.data.todayWorkTypeStatistic.forEach((item) => {
          topData.jobTypeStatistics.typeArr.push(item.workType);
          topData.jobTypeStatistics.numArr.push(item.count);
        });
        initJobTypeChart();

        //每日各时段进出场人数分布
        res.data.todayAttendenceTrend.forEach((item) => {
          topData.entryTrend.hours.push(item.hour);
          topData.entryTrend.yData[0].value.push(item.inNum);
          topData.entryTrend.yData[1].value.push(item.outNum);
        });
        initEntrySituationChart();
      } else {
        errorTip.value = res.data.msg;
      }
    });
  window.onresize = _.debounce(() => {
    myJobTypeChart.resize();
    myEntrySituationChart.resize();
  }, 300);
};

const entryExitLoading = ref(false);
const total = ref(0);
const initStaffTable = () => {
  entryExitLoading.value = true;
  api.staff.getPersonInfoList(bottomData.form).then((res) => {
    if (res.data.status) {
      bottomData.tableData = res.data.data;
      total.value = bottomData.total = res.data.totalCount;
      if (bottomData.tableData.length > 0) {
        bottomData.currentRowKey = bottomData.tableData[0]._id;
        handleRowClick(bottomData.tableData[0]);
      } else {
        bottomData.currentRowKey = "";
      }
    } else {
      ElMessage.error(res.data.msg);
    }
    entryExitLoading.value = false;
  });
};

//搜索
const onSubmit = function () {
  bottomData.form.searchText = bottomData.personName;
  bottomData.form.pageIndex = 0;
  initStaffTable();
};

//重置
const onReset = function () {
  bottomData.personName = bottomData.form.searchText = "";
  initStaffTable();
};

//表格key赋值
const getRowKeys = function (row) {
  return row._id;
};

const infoLoading = ref(false);
const handleRowClick = (row, column, event) => {
  bottomData.currentRowKey = row._id;
  infoLoading.value = true;
  api.staff.getPersonInfoDetailById({ idCardNo: row.idCardNo }).then((res) => {
    bottomData.detailInfo.baseInfo = res.data;
    bottomData.detailInfo.simpleInfo[0].value = res.data.personName;
    bottomData.detailInfo.simpleInfo[1].value = res.data.workType;
    bottomData.detailInfo.simpleInfo[2].value = res.data.teamName;
    bottomData.detailInfo.simpleInfo[3].value = res.data.enterpriseName;
    infoLoading.value = false;
  });
};

const initJobTypeChart = () => {
  let chartJobTypeDom = document.getElementById("jobTypeChart");
  echarts.dispose(chartJobTypeDom);
  myJobTypeChart = echarts.init(jobTypeChartRef.value);
  myJobTypeChart.clear();
  let option;
  option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      left: "3%",
      right: "6%",
      bottom: "3%",
      top: "10%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: topData.jobTypeStatistics.typeArr,
      axisLabel: {
        interval: 0,
        color: "#5D605F",
        fontFamily: "SourceHanSansSC",
        interval: 0,
        rotate: 30,
      },
      axisTick: {
        show: false, //不显示坐标轴刻度线
      },
      axisLine: {
        show: true, //不显示坐标轴线
        lineStyle: {
          color: "#939393 ",
        },
      },
    },
    yAxis: {
      type: "value",
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#5D605F",
        fontFamily: "SourceHanSansSC",
      },
    },
    series: [
      {
        name: "工种统计",
        type: "bar",
        data: topData.jobTypeStatistics.numArr,
        barWidth: 8,
        label: {
          show: true,
          position: "top",
          formatter: "{c}人",
        },
        itemStyle: {
          // 使用方法二的写法
          color: {
            type: "linear",
            x: 0, //右
            y: 0, //下
            x2: 1, //左
            y2: 0, //上
            colorStops: [
              {
                offset: 0,
                color: "#C5CAF8", // 0% 处的颜色
              },
              {
                offset: 1,
                color: "#8C8FF7", // 100% 处的颜色
              },
            ],
          },
          normal: {
            barBorderRadius: [0, 0, 0, 0],
          },
        },
      },
    ],
  };
  option && myJobTypeChart.setOption(option);
};

const colors = ["#00A0E9", "#FE5632"];
const initEntrySituationChart = () => {
  let chartEntrySituationDom = document.getElementById("entrySituationChart");
  echarts.dispose(chartEntrySituationDom);
  myEntrySituationChart = echarts.init(entrySituationChartRef.value);
  myEntrySituationChart.clear();

  const series = [];
  topData.entryTrend.yData.forEach((item, index) => {
    series.push({
      name: item.title,
      data: item.value,
      type: "line",
      barWidth: 25,
      smooth: true,
      symbol: "none",
      lineStyle: {
        normal: {
          width: 5,
          color: {
            type: "linear",
            colorStops: [
              {
                offset: 0,
                color: colors[index], // 0% 处的颜色
              },
              {
                offset: 1,
                color: colors[index] + "90", // 100% 处的颜色
              },
            ],
            globalCoord: false, // 缺省为 false
          },
          // shadowColor: colors[index] + "90",
          // shadowBlur: 5,
          // shadowOffsetY: 10,
        },
      },
      itemStyle: {
        normal: {
          color: colors[index],
          borderWidth: 10,
        },
      },
    });
  });

  let option = {
    grid: {
      x: 40,
      y: 40,
      x2: 40,
      y2: 40,
    },
    legend: {
      textStyle: {
        color: "#666",
        fontSize: 12,
        fontFamily: "SourceHanSansSC",
      },
      itemGap: 20,
      itemWidth: 10,
      itemHeight: 5,
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        // 坐标轴指示器，坐标轴触发有效
        type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
      },
    },
    xAxis: {
      type: "category",
      name: "(h)",
      nameTextStyle: {
        padding: [0, 0, 0, -10],
        fontFamily: "SourceHanSansSC",
      },
      data: topData.entryTrend.hours,
      axisLabel: {
        interval: 0,
        color: "#5D605F",
        fontFamily: "SourceHanSansSC",
      },
      axisTick: {
        show: false, //不显示坐标轴刻度线
      },
      axisLine: {
        show: true, //不显示坐标轴线
        lineStyle: {
          color: "#939393 ",
        },
      },
    },
    yAxis: {
      type: "value",
      name: "(人)",
      nameLocation: "end",
      nameTextStyle: {
        padding: [0, 0, 0, -10],
        fontFamily: "SourceHanSansSC",
      },
      axisTick: {
        show: false, //不显示坐标轴刻度线
      },
      axisLabel: {
        color: "#5D605F",
        fontFamily: "SourceHanSansSC",
      },
      axisLine: {
        show: true, //不显示坐标轴线
        lineStyle: {
          color: "#939393 ",
        },
      },
      splitLine: {
        //网格线
        show: true,
        lineStyle: {
          type: "dashed",
        },
      },
    },
    series: series,
  };
  myEntrySituationChart.setOption(option);
};

//分页
const handlePageChange = function (pageNum) {
  bottomData.form.pageIndex = pageNum - 1;
  initStaffTable();
};
</script>

<template>
  <div class="staff">
    <div class="staffTop" v-loading="topLoading">
      <div class="staffTopItem fieldCondition">
        <div class="title">今日现场概况</div>
        <el-empty v-if="errorTip" :image-size="100" :description="errorTip" />
        <div v-else>
          <div class="fieldItem">
            <img src="@/assets/images/staff/p1.png" /><span>当前在场人数<span class="onsiteSpan">{{
              topData.fieldCondition.onSiteNum
            }}</span>人</span>
          </div>
          <div class="fieldItem">
            <img src="@/assets/images/staff/p2.png" /><span>今日出勤人数<span class="attendanceSpan">{{
              topData.fieldCondition.attendanceNum
            }}</span>人</span>
          </div>
        </div>
      </div>
      <div class="staffTopItem">
        <div class="title">工种统计</div>
        <el-empty v-if="errorTip" :image-size="100" :description="errorTip" />
        <div v-else ref="jobTypeChartRef" id="jobTypeChart"></div>
      </div>
      <div class="staffTopItem">
        <div class="title">今日各时段进出场人数分布</div>
        <el-empty v-if="errorTip" :image-size="100" :description="errorTip" />
        <div v-else ref="entrySituationChartRef" id="entrySituationChart"></div>
      </div>
    </div>
    <div class="staffBottom">
      <div class="tableContainer">
        <div class="title">人员列表</div>
        <div class="toolbar">
          <el-form :model="bottomData.form" label-width="100px">
            <el-form-item label=" " label-width="0px">
              <el-input size="small" v-model="bottomData.personName" placeholder="请输入关键字" />
            </el-form-item>
            <el-form-item class="btns">
              <el-button :icon="Search" size="small" type="primary" color="#8F93F7" style="color: #ffffff"
                @click="onSubmit">搜索</el-button>
              <el-button color="#FFFFFF" :icon="Refresh" size="small" type="primary" @click="onReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="total">
          记录共<b>{{ total }}</b>条
        </div>
        <el-table :data="bottomData.tableData" :highlight-current-row="true" :current-row-key="bottomData.currentRowKey"
          :row-key="getRowKeys" style="width: 98%; margin: 0 auto" height="calc(100vh - 560px)"
          @row-click="handleRowClick" v-loading="entryExitLoading">
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column prop="enterpriseName" label="参建单位" align="center" />
          <el-table-column prop="teamName" label="班组名称" align="center" />
          <el-table-column prop="personName" label="工人姓名" align="center" />
          <el-table-column prop="workType" label="工种/岗位" align="center" />
          <el-table-column prop="role" label="人员类型" align="center" />
        </el-table>
        <div class="pagination">
          <el-pagination :current-page="bottomData.form.pageIndex + 1" :page-size="bottomData.pageSize"
            :total="bottomData.total" layout="prev,pager,next" background @current-change="handlePageChange">
          </el-pagination>
        </div>
      </div>
      <div class="detailInfo" v-loading="infoLoading">
        <div class="title">基本信息</div>
        <el-empty v-if="!bottomData.tableData.length" :image-size="100" description="暂无数据" />
        <div v-else>
          <div class="simpleInfo">
            <div class="l-p">
              <el-image style="width: 160px; height: 180px" :src="bottomData.detailInfo.baseInfo.faceUrl" fit="cover"
                :preview-src-list="[bottomData.detailInfo.baseInfo.faceUrl]">
                <template #error>
                  <div class="image-slot">
                    <span class="unimg">暂无图片</span>
                  </div>
                </template>
              </el-image>
            </div>
            <div class="infoList">
              <div class="infoItem" v-for="item in bottomData.detailInfo.simpleInfo" :key="item.type">
                <img :src="item.src" />
                <span class="label">{{ item.label }}:</span>
                <span class="value">{{ item.value }}</span>
              </div>
            </div>
          </div>
          <div class="baseInfo">
            <el-form :inline="true" label-position="left">
              <el-form-item label="性别:">
                <span>{{ bottomData.detailInfo.baseInfo.gender }}</span>
              </el-form-item>
              <el-form-item label="民族:">
                <span>{{ bottomData.detailInfo.baseInfo.national }}</span>
              </el-form-item>
              <el-form-item label="年龄:">
                <span>{{ bottomData.detailInfo.baseInfo.age }}</span>
              </el-form-item>

              <el-form-item label="身份证号:">
                <span>{{ cardHide(bottomData.detailInfo.baseInfo.idCardNo) }}</span>
              </el-form-item>
              <el-form-item label="出生:">
                <span>{{ bottomData.detailInfo.baseInfo.birthDate }}</span>
              </el-form-item>
              <el-form-item label="用工日期:">
                <span>{{
                  formatDate(bottomData.detailInfo.baseInfo.startTime)
                }}</span>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.staff {
  width: 100%;
  height: calc(100vh - 82px);
  overflow-x: hidden;
  overflow-y: auto;

  .staffTop {
    width: 100%;
    overflow: hidden;

    :deep .el-empty {
      padding: 0px;
    }

    .staffTopItem {
      float: left;
      position: relative;
      width: calc(33.3% - 18px);
      height: 230px;
      margin: 0 8px;
      background-color: white;
      border: 1px solid #dce3ef;
      box-shadow: 2px 2px 0px 0px rgba(236, 238, 252, 0.32);
      border-radius: 6px;

      .title {
        height: 20px;
        padding-left: 5px;
        margin: 10px;
        font-size: 16px;
        font-family: Source Han Sans SC;
        font-weight: 600;
        color: #656565;
        line-height: 20px;
        border-left: 3px solid #8f93f7;
      }
    }
  }

  .staffBottom {
    width: 100%;
    display: flex;

    .tableContainer {
      position: relative;
      width: 66%;
      height: calc(100% - 317px);
      margin-top: 8px;
      margin-left: 8px;
      border: 1px solid #dce3ef;
      box-shadow: 2px 2px 0px 0px rgba(236, 238, 252, 0.32);
      border-radius: 6px;
      overflow: hidden;

      .title {
        position: absolute;
        top: 9px;
        height: 20px;
        padding-left: 5px;
        margin-left: 10px;
        font-size: 16px;
        font-family: Source Han Sans SC;
        font-weight: 600;
        color: #656565;
        line-height: 20px;
        border-left: 3px solid #8f93f7;
      }

      .total {
        width: 100%;
        height: 35px;
        text-indent: 20px;

        b {
          color: #8f93f7;
          font-size: 20px;
          padding: 0px 5px;
        }
      }

      .pagination {
        width: 100%;
        display: flex;
        justify-content: center;
        padding: 10px;
        box-sizing: border-box;
        padding-top: 10px;
        background: #ffffff;
      }

      .toolbar {
        display: flex;
        align-items: center;
        margin-top: 35px;
        margin-bottom: 5px;

        :deep .el-form {
          .el-form-item {
            margin-left: 10px;
            float: left;
            margin-bottom: 10px;
          }

          .el-form-item__label {
            color: #656565;
          }
        }

        .btns {
          :deep .el-form-item__content {
            margin-left: 10px !important;
            margin-top: 4px;
          }
        }
      }

      :deep .el-table th.el-table__cell {
        background-color: #ecedff;
      }

      :deep .el-table {
        min-height: 425px;

        .el-table__inner-wrapper {
          min-height: 425px;
        }
      }
    }

    .detailInfo {
      position: relative;
      width: 32%;
      height: calc(100% - 465px);
      margin-top: 8px;
      margin-left: 15px;
      border: 1px solid #dce3ef;
      box-shadow: 2px 2px 0px 0px rgba(236, 238, 252, 0.32);
      border-radius: 6px;
      overflow: hidden;

      .title {
        position: absolute;
        top: 9px;
        height: 20px;
        padding-left: 5px;
        margin-left: 10px;
        font-size: 16px;
        font-family: Source Han Sans SC;
        font-weight: 600;
        color: #656565;
        line-height: 20px;
        border-left: 3px solid #8f93f7;
      }

      .simpleInfo {
        width: 95%;
        margin: 45px 0 20px 0;
        padding-left: 15px;
        display: flex;

        .infoList {
          position: relative;
          width: 70%;
          overflow: hidden;
          margin-left: 20px;

          .infoItem {
            overflow: hidden;
            text-overflow: ellipsis; //文本溢出显示省略号
            white-space: nowrap; //文本不会换行

            img {
              width: 35px;
            }

            margin-bottom: 18px;

            .label {
              padding: 0px 10px;
            }
          }
        }

        .l-p {
          width: 160px;
          height: 180px;
          border: 1px solid #eef3fd;
          text-align: center;
          padding: 5px;

          :deep .image-slot {
            height: 180px;
          }

          .unimg {
            text-align: center;
            line-height: 180px;
            color: #9c9c9c;
          }
        }
      }

      .baseInfo {
        box-sizing: border-box;
        width: 97%;
        height: 150px;
        margin: 0 auto;
        background: #ecedff;
        border-radius: 6px;
        padding-left: 41px;
        padding-top: 20px;
        margin-bottom: 15px;
      }

      :deep .el-table th.el-table__cell {
        background-color: #ecedff;
      }

      :deep .el-form-item {
        margin-bottom: 0px;
      }

      :deep .el-form-item__content {
        width: 130px;
      }
    }
  }
}

.fieldCondition {
  .fieldItem {
    padding-left: 17%;
    margin-bottom: 10px;
  }

  img {
    width: 50px;
    padding-right: 10px;
  }
}

.onsiteSpan {
  font-size: 50px;
  font-family: Source Han Sans SC;
  font-weight: 500;
  color: #78c8ff;
  padding: 20px;
}

.attendanceSpan {
  font-size: 50px;
  font-family: Source Han Sans SC;
  font-weight: 500;
  color: #70e3ae;
  line-height: 70px;
  padding: 20px;
}

#entrySituationChart {
  width: 100%;
  height: 190px;
}

#jobTypeChart {
  width: 100%;
  height: 190px;
}

// @media only screen and (max-width: 1885px) {
//     .staff .staffTop .staffTopItem {
//         width: 23.5%;
//     }
// }

@media only screen and (max-width: 1750px) {
  .staff .staffBottom .detailInfo .baseInfo {
    padding-left: 10px;
  }

  .el-form--inline .el-form-item {
    margin-right: 0px;
  }
}

@media only screen and (max-width: 1830px) {
  .staff .staffBottom .detailInfo .simpleInfo .infoList {
    margin-left: 0px;
    margin-right: 0px;
  }

  .staff .staffBottom .detailInfo .simpleInfo .infoList .infoItem img {
    width: 25px;
  }
}
</style>